package com.tianmenguide.wxapi;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.tianmenguide.common.core.domain.AjaxResult;
import cn.hutool.http.HttpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/wxapi")
@RequiredArgsConstructor
@Api(tags = "天气wxapi")
public class WxWeatherController {

    // 固定的天气API URL和API Key
    private static final String WEATHER_API_URL = "https://api.seniverse.com/v3/weather/now.json";
    private static final String API_KEY = "SqYvg547BOGqLtzrG";

    @GetMapping("/weather")
    @ApiOperation("查询天气信息")
    public AjaxResult getWeatherInfo() {
        try {
            // 构建请求URL
            String urlString = String.format("%s?key=%s&location=dalian&language=zh-Hans&unit=c", WEATHER_API_URL, API_KEY);

            // 使用 Hutool 的 HttpUtil 发送 GET 请求
            String response = HttpUtil.get(urlString);

            // 解析返回的 JSON 字符串
            JSONObject responseJson = JSON.parseObject(response);

            // 提取 'results' 数组中的数据
            JSONObject result = responseJson.getJSONArray("results").getJSONObject(0);

            // 提取 location 和 now 的信息
            JSONObject location = result.getJSONObject("location");
            JSONObject now = result.getJSONObject("now");

            // 获取位置和天气信息
            String locationName = location.getString("name");
            String country = location.getString("country");
            String weatherText = now.getString("text");
            String temperature = now.getString("temperature");

            // 构建并返回格式化后的结果
            String formattedMsg = String.format("当前天气: %s  温度: %s°C",
                    weatherText, temperature);

            return AjaxResult.success(formattedMsg);
        } catch (Exception e) {
            // 错误处理
            return AjaxResult.error("获取天气信息失败：" + e.getMessage());
        }
    }
}
